package gov.mogaha.ntis.cmm.mob.law.activity;





import gov.mogaha.ntis.cmm.mob.R;
import gov.mogaha.ntis.cmm.mob.baseactivity.BaseActivity;
import gov.mogaha.ntis.cmm.mob.law.adapter.CmmMobLawListAdapter;
import gov.mogaha.ntis.cmm.mob.law.handler.CmmMobLawXmlHandler;
import gov.mogaha.ntis.cmm.mob.law.util.CmmMobLawHttpUtil;
import gov.mogaha.ntis.cmm.mob.law.util.CmmMobLawStr;
import gov.mogaha.ntis.cmm.mob.law.util.CmmMobLawXmlUtil;
import gov.mogaha.ntis.cmm.mob.law.view.CmmMobLawTitleView;
import gov.mogaha.ntis.cmm.mob.law.vo.CmmMobLawVO;
import gov.mogaha.ntis.cmm.mob.util.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;


public class CmmMobLawListActivity extends BaseActivity {
	
	// 법령 내용에서 법령조회 App 종료할떄 필요한 변수
	public static Activity mainActivity;
	
	ArrayList<CmmMobLawVO> listData = new ArrayList<CmmMobLawVO>();
	CmmMobLawVO vo;
	
	boolean isBusy = false;
	int visibleItemCnt;
	int page;
	int lastPosition;
	
	ListView lv;
	EditText et;
	
	ProgressDialog dial;
	
	CmmMobLawTitleView cmmMobLawTitleView;
	Button prevBtn;
	Button exitBtn;
	ImageButton clsBtn;
	
	InputMethodManager imm;
	ActivityManager am;
	
	    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainActivity = this;
        
        dial = new ProgressDialog(CmmMobLawListActivity.this);
        dial.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dial.setMessage("Wait a monent...");
        
        // ActivityManager 의 RestartPackage API를 호출
        am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
        
        imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
        
        /* Title 1 Start*/
        // Custom Title Bar
		// Title Bar 의 Size 는 고정, 새로로 긴 타이틀 바를 사용하면 짤린다.
		// Title Bar 의 세로 사이즈를 늘리려면 테마값으로 적용해야 한다.
		// 요즘은 Action Bar 라고 해서 모든 화면에 비슷한 Custom Title Bar가 들어간다면 
		// 임의의 Custom View 를 작성해서 타이틀 바로 많이 사용...
        /*
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.law_search);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
        TextView title = (TextView) findViewById(R.id.title_text);
        title.setText(CmmStr.TITLE_NAME);
        */
        /* Title 1 End*/
        
        /* Title 2 Start*/
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.cmmmoblawsearch);
        this.cmmMobLawTitleView = (CmmMobLawTitleView) findViewById(R.id.title_view);
		this.cmmMobLawTitleView.setTitle(CmmMobLawStr._TITLE_NAME, 16);
		this.prevBtn = this.cmmMobLawTitleView.openLeftBtn();
		this.prevBtn.setVisibility(View.INVISIBLE);
		/*
		this.prevBtn.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		*/
		this.exitBtn = this.cmmMobLawTitleView.openRightBtn();
		this.exitBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// 종료
				mDialogHandler.sendEmptyMessage(DIALOG_ID_CLOSE);
			}
		});
		/* Title 2 End*/
		
        lv = (ListView)findViewById(R.id.listView);
        et = (EditText)findViewById(R.id.searchText);
        clsBtn = (ImageButton)findViewById(R.id.clear_btn);
        
        // EditText에 Text의 변화 알기
        et.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			public void afterTextChanged(Editable s) {
				if(et.getText().length()==1){
					clsBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.icon_select_off));
					clsBtn.setVisibility(View.VISIBLE);
				}else if(et.getText().length()==0){
					clsBtn.setVisibility(View.INVISIBLE);
				}
				
			}
		});
        
        clsBtn.setOnTouchListener(new OnTouchListener() {
			
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {   
				    // when you press it down, it's gonna swap to a sort of "selected" image   
				    clsBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.icon_select_on));   
				} else if (event.getAction() == MotionEvent.ACTION_UP) {   
				    // when you release the button the text will be cleared up and then disappear right afterward   
				    et.setText("");
				    clsBtn.setVisibility(View.INVISIBLE);   
				}   

				return false;
			}
		});
        
        // register "Search" button about "OnClickListener" event 
        Button btnSearch = (Button)findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// initial variable
				lastPosition = 0;
				page = 1;
				
				getData();
			}
		});
        
        // 상세페이지 들어갈 때 Event 등록
        lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(CmmMobLawListActivity.this, CmmMobLawContentActivity.class);
				intent.putExtra("url", listData.get(position).lawUrl);
				intent.putExtra("searchText", et.getText().toString());
				intent.putExtra("page", page);
				intent.putExtra("lastPosition", lastPosition);
				intent.putExtra("visibleItemCnt", visibleItemCnt);
				intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				startActivityForResult(intent,INTENT_REGUEST_CODE_DEFAULT);
				//overridePendingTransition(R.anim.fade, R.anim.hold);
			}
		});
        
        
        lv.setOnScrollListener(new OnScrollListener() {
			
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					isBusy = false;
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				case OnScrollListener.SCROLL_STATE_FLING:
					isBusy = true;
					break;
				default:
					break;
				}
			}
			
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
							
				int lastItem = firstVisibleItem + visibleItemCount;
				//Log.d(CmmMobLawStr._DEBUG, "firstVisibleItem / visibleItemCount : " + firstVisibleItem + "/" + visibleItemCount);
				//Log.d(CmmMobLawStr._DEBUG, "lastItem / totalItemCount / isBusy : " + lastItem + "/" + totalItemCount + "/" + (isBusy?"Busy":"Not Busy"));
				visibleItemCnt = visibleItemCount;
				if (lastItem == totalItemCount && isBusy) {
					//dial.show();
					lastPosition = lastItem;
					page++;
					isBusy = false;
					getData();
				}
				
			}
		});
        //dial = ProgressDialog.show(CmmMobLawListActivity.this, "", "Wait a monent...", true);
        //handler.sendEmptyMessage(2);
        
     // 타 화면에서 넘어 왔을 경우 Search 
	 Intent intent = getIntent();
	 String searchText = intent.getStringExtra("searchText");
	 
	 if(searchText != null){
		 et.setText(searchText);
		 //키보드 숨기기
		 //imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
		 
		 // initial variable Start
		 String tmpPage = intent.getStringExtra("page");
		 
		 // 상세페이지에서 나왔을 경우
		 if(tmpPage != null && !"".equals(tmpPage)){
			 page = Integer.parseInt(tmpPage);
			 lastPosition = Integer.parseInt(intent.getStringExtra("lastPosition"));
			 visibleItemCnt = Integer.parseInt(intent.getStringExtra("visibleItemCnt"));
	     // 다른 화면에서 넘어 왔을 경우
		 }else{
			 lastPosition = 0;
			 page = 1; 
		 }
		// initial variable End
		 getData();
	 }
        
    }
    
    Handler handler = new Handler(){
    	public void handleMessage(Message msg){
    		switch(msg.what){
    		case 0:
    			Logger.d( "handler 0");
    			dial.show();
    			break;
    		case 1:
    			Logger.d( "handler 1");
    			
    			CmmMobLawXmlHandler CmmMobLawXmlHandler;
    			CmmMobLawXmlHandler = (CmmMobLawXmlHandler) msg.obj;
    			
    			Logger.d( "Data Size : " + CmmMobLawXmlHandler.getList().size());
    			Logger.d( "page : " + page);
    			// Search Button 눌렀을 경우 기존 데이터 삭제
    			if(page == 1){
    				listData = new ArrayList<CmmMobLawVO>();
    			}
    			
    			if(page == 1 && CmmMobLawXmlHandler.getList().size() == 0){
    				Toast.makeText(CmmMobLawListActivity.this, CmmMobLawStr._ERROR_MESSAGE_1, Toast.LENGTH_SHORT).show();
    				makeViewList(lv, listData);
    			}else if(page != 1 && CmmMobLawXmlHandler.getList().size() == 0){
    				Toast.makeText(CmmMobLawListActivity.this, CmmMobLawStr._ERROR_MESSAGE_2, Toast.LENGTH_SHORT).show();
    			}else{
        			if (CmmMobLawXmlHandler.getList().size() > 0) {
        				for (CmmMobLawVO tmp : CmmMobLawXmlHandler.getList()) {
        					listData.add(tmp);
        				}
        			}

        			if (listData != null && listData.size() < 1) {
        				Toast.makeText(CmmMobLawListActivity.this, CmmMobLawStr._ERROR_MESSAGE_1,
        						Toast.LENGTH_SHORT).show();
        			}
        			
        			makeViewList(lv, listData);
        			
        			if (page != 1) {
        				lv.setSelection(lastPosition - visibleItemCnt);	
        			}
    			}
    			dial.dismiss();
    			break;
    		case 2:
    			
    			dial.dismiss();
    			break;
    		default:
    			break;
    		}
    		
    	}
    };

   
    public void getData(){
    	// 키보드 숨기기
		//imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
		
    	dial.show();
    	new Thread(new Runnable() {
    		
    		public void run() {
    			Message msg = Message.obtain();
    			String data = CmmMobLawHttpUtil.sendHttpPost(CmmMobLawStr._LAWURL+CmmMobLawStr._ACTION1, makeURL(et.getText().toString(), ""));
    			CmmMobLawXmlHandler CmmMobLawXmlHandler = new CmmMobLawXmlHandler();
    			CmmMobLawXmlUtil.parseXml(data, CmmMobLawXmlHandler);
    			
    			msg.what = 1;
    			msg.obj = CmmMobLawXmlHandler;
    			
    			handler.sendMessage(msg);
    		}
    	}).start();
    }
    
    public void makeViewList(ListView lv, ArrayList<CmmMobLawVO> list){
    	CmmMobLawListAdapter adapter = new CmmMobLawListAdapter(this, R.layout.cmmmoblawsearchrow, list);
    	lv.setAdapter(adapter);
    }
    
    public ArrayList<HashMap<String, String>> makeURL(String searchText, String target){
    	ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
    	HashMap<String, String> hm;
    	
    	// Search Target
    	if("".equals(target) || CmmMobLawStr._LAW.equals(target)){
    		hm = new HashMap<String, String>();
    		hm.put(CmmMobLawStr._TARGET, CmmMobLawStr._LAW);
    		list.add(hm);
    	}
    	
    	// Search Keyword
    	if(searchText != null && !"".equals(searchText)){
    		hm = new HashMap<String, String>();
    		try {
				hm.put(CmmMobLawStr._QUERY, URLEncoder.encode(searchText,"UTF-8"));
			} catch (UnsupportedEncodingException e) {
				Log.e(CmmMobLawStr._ERROR, "ERROR : CmmMobLawListActivity makeURL");
			}
    		list.add(hm);
    	}
    	
    	// Page Setting
    	hm = new HashMap<String, String>();
    	hm.put(CmmMobLawStr._PAGE, String.valueOf(page));
    	list.add(hm);
    	
    	return list;
    }
}